package com.uni.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uni.base.RestResponse;
import com.uni.pojo.Provider;
import com.uni.service.ProviderService;
import com.uni.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @作者: Unirithe
 * @日期: 2022/2/21
 **/

@RestController
@RequestMapping("/admin/provider")
public class ProviderAdminController {
    @Autowired
    private ProviderService providerService;
    private int pageSize = 6;

    @PostMapping("/query")
    public String querySomeProviders(@RequestBody(required = false) Map<String, String> paramMap){
        Integer pageNow = paramMap == null ? 1 : Integer.parseInt(paramMap.getOrDefault("pageNow", "1"));
        PageHelper.startPage(pageNow, pageSize);
        List<Provider> providers = providerService.getBySome(paramMap);
        PageInfo pageInfo = PageUtil.setPageInfo(pageNow, pageSize, providers);
        return providers != null ? RestResponse.ok(
                new HashMap<String, Object>(){{
                    put("pageInfo", pageInfo);
                }}
        ).toJSONString()
                : RestResponse.fail("获取供应商失败").toJSONString();
    }
    @PostMapping("/query/{prodId}")
    public String queryProviderById(@PathVariable Long prodId){
        Provider provider = providerService.getByProviderId(prodId);
        return provider != null ? RestResponse.ok(provider).toJSONString()
                : RestResponse.fail("获取供应商失败").toJSONString();
    }
    @PostMapping("/queryall")
    public String queryAllProvider(){
        List<Provider> providers = providerService.getAll();
        return providers != null ? RestResponse.ok(providers).toJSONString()
                : RestResponse.fail("获取所有供应商失败").toJSONString();
    }
    @PostMapping("/update")
    public String updateProvider(Provider provider){
        Provider prov = providerService.autoModifyById(provider);
        return prov == null ?
                RestResponse.fail("更新供应商信息失败.").toJSONString() :
                RestResponse.ok("修改成功!").toJSONString();
    }

    @PostMapping("/add")
    public String addProvider(Provider provider){
        int i = providerService.addProvider(provider);
        return i == 1 ? RestResponse.ok("添加成功!").toJSONString()
                : RestResponse.fail("添加失败.").toJSONString();
    }

    @PostMapping("/delete")
    public String removeProvider(@RequestBody Map<String, Object> map){
        List<Long> ids = (List<Long>) map.get("ids");
        int i = providerService.removeProviderByIds(ids);
        return i >= ids.size() ?
                RestResponse.ok("删除成功!").toJSONString()
                : RestResponse.fail("删除失败.").toJSONString();
    }
}
